<?php

namespace app\common\model;

use think\Db;
use think\Model;


class ShipRemind extends Model
{

    

    

    // 表名
    protected $name = 'ship_remind';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'create_time';
    protected $updateTime = 'update_time';
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
		'status_text'
    ];
    
	const STATUS_WAIT_EXPORT = 0;
	const STATUS_WAIT_SEND = 1;
	const STATUS_WAIT_SING = 2;
	const STATUS_DONE = 3;
	const STATUS_CANCEL = -1;
    
	public static $statusList = [
//		self::STATUS_CANCEL => '已取消',
		self::STATUS_WAIT_EXPORT => '待导出',
		self::STATUS_WAIT_SEND => '已导出',
//		self::STATUS_WAIT_SING => '待签收',
//		self::STATUS_DONE => '已完成'
	];

	public function getStatusTextAttr($value, $data) {
		$value = $value ? : $data['status'];
		$list = self::$statusList;
		return $list[$value] ??'';
	}
	
	public function agent() {
		return $this->belongsTo('agentShop', 'agent_id', 'id', '', 'left')->setEagerlyType(0);
	}
	
	
	public function goods() {
		return $this->belongsTo('goods', 'goods_id', 'id', '', 'left')->setEagerlyType(0);
	}
	public function spec() {
		return $this->belongsTo('goodsSpec', 'spec_id', 'id', '', 'left')->setEagerlyType(0);
	}
	
	/**
	 * 添加记录
	 * @param $agentId 代理ID
	 * @param $goodsId 商品ID
	 * @param $specId 规格ID
	 * @param $number 数量
	 * @return bool|false|int
	 * @throws \think\db\exception\DataNotFoundException
	 * @throws \think\db\exception\ModelNotFoundException
	 * @throws \think\exception\DbException
	 */
	public function addRow($agentId, $goodsId, $specId, $number) {
		$row = Db::name('shipRemind')
			->where([
				'agent_id' => $agentId,
				'goods_id' => $goodsId,
				'spec_id' => $specId,
				'status' => ['in', [self::STATUS_WAIT_EXPORT, self::STATUS_WAIT_SEND, self::STATUS_WAIT_SING]]
			])
			->order(['create_time' => 'desc'])
			->find();
		
		//要完成了才再添加新数据
		if($row) {
			return true;
		}
		
		$res = $this->isUpdate(false)
			->save([
				'agent_id' => $agentId,
				'goods_id' => $goodsId,
				'spec_id' => $specId,
				'number' => $number
			]);
		
		return $res;
	}


}
